package com.itheima.controller;

import com.itheima.utils.UploadUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {
    @PostMapping(value = "/upload", produces = {"text/html;charset=UTF-8"})
    public String upload(String pdesc, MultipartFile upload, HttpServletRequest request) {
        System.out.println("图片描述为:" + pdesc);
        String realPath = request.getSession().getServletContext().getRealPath("file/" + UploadUtils.getDir());
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String fileName = upload.getOriginalFilename();
        String uuidName = UploadUtils.getUUIDName(fileName);
        try {
            upload.transferTo(new File(file, uuidName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传文件成功!";
    }
}
